<template>
	<div :class="['navbar', { transparent: isHomePage }]">
		<div class="navbar-left">
			<div class="title">花都优居平台</div>
			<ul class="menu" v-if="!isAdmin">
				<li :class="{ active: activeKey === 'home' }" @click="navigateTo('/home-page')">首页</li>
				<li :class="{ active: activeKey === 'list' }" @click="navigateTo('/house-list')">租房</li>
			</ul>
		</div>
		<div class="navbar-right">
			<!-- 未登录 -->
			<template v-if="!isLoggedIn">
				<text class="login-text" @click="navigateTo('/login')">登录/注册</text>
			</template>
			<!-- 已登录 -->
			<template v-else>
				<a-dropdown trigger="hover">
					<a class="ant-dropdown-link">
						<span class="username">{{ username }}</span>
						<DownOutlined style="margin-left: 0.5rem" />
					</a>
					<template #overlay>
						<ul class="dropdown-menu">
							<li @click="goToPersonalCenter" v-if="!isAdmin">个人中心</li>
							<li @click="goToChat" v-if="!isAdmin">在线聊天</li>
							<li @click="logout">退出登录</li>
						</ul>
					</template>
				</a-dropdown>
			</template>
		</div>
	</div>
</template>

<script>
	import { DownOutlined } from '@ant-design/icons-vue';
	import eventBus from '@/utils/eventBus';
	import { Modal } from 'ant-design-vue'; // 引入事件总线

	export default {
		name: 'Navbar',
		components: {
			DownOutlined
		},
		data() {
			return {
				isLoggedIn: false,
				username: '',
				activeKey: '', // 当前选中的菜单项
				isAdmin: false //当前是否是管理员
			};
		},
		computed: {
			isHomePage() {
				return this.$route.path === '/home-page'; // 判断是否是首页
			},
			isAdmin() {
				//如果当前是管理员，返回truue
				if (localStorage.getItem('role') === 'admin') {
					return true;
				}
			}
		},
		methods: {
			logout() {
				Modal.confirm({
					title: '确认退出登录？',
					content: '您确定要退出登录吗？',
					okText: '确定',
					cancelText: '取消',
					onOk: () => {
						localStorage.removeItem('satoken'); // 清除 token
						localStorage.removeItem('name'); // 清除用户名
						localStorage.removeItem('id'); // 清除用户名
						localStorage.removeItem('role');
						this.isLoggedIn = false;
						this.username = '';
						this.$message.success('已退出登录');
						this.$router.push('/home-page');
					}
				});
			},
			loadUserInfo() {
				const token = localStorage.getItem('satoken');
				const username = localStorage.getItem('name');
				if (token && username) {
					this.isLoggedIn = true;
					this.username = username;
				}
			},
			updateActiveKey(path) {
				// 根据路由规则动态设置 activeKey
				if (path === '/home-page') {
					this.activeKey = 'home';
				} else if (path.startsWith('/house-list') || path.startsWith('/house-details')) {
					this.activeKey = 'list';
				} else {
					this.activeKey = ''; // 默认无高亮
				}
			},
			navigateTo(path) {
				// 记录当前页面的路由（上一个页面的路由）
				const fromPath = this.$route.fullPath;
				sessionStorage.setItem('fromPath', fromPath);
				this.$router.push(path).then(() => {
					window.location.reload();
				});
			},
			// 根据角色跳转到对应个人中心
			goToPersonalCenter() {
				if (localStorage.getItem('role') === 'user') {
					this.navigateTo('/user-center');
				} else if (localStorage.getItem('role') === 'landlord') {
					this.navigateTo('/landlord-center');
				} else if (localStorage.getItem('role') === 'admin') {
					this.navigateTo('/admin-center');
				} else {
					this.$message.warning('请先登录');
				}
			},
			// 根据角色跳转到对应个人中心
			goToChat() {
				if (localStorage.getItem('role') === 'user') {
					this.navigateTo('/user-chat');
				} else if (localStorage.getItem('role') === 'landlord') {
					this.navigateTo('/landlord-chat');
				}
			}
		},

		created() {
			// 初始化 activeKey
			this.updateActiveKey(this.$route.path);

			// 监听路由变化，实时更新 activeKey
			this.$watch('$route.path', (newPath) => {
				this.updateActiveKey(newPath);
			});

			// 初始化用户信息
			this.loadUserInfo();

			// 监听登录事件
			eventBus.on('userLoggedIn', this.loadUserInfo);

			// 监听用户名变化事件
			eventBus.on('usernameChanged', this.loadUserInfo);
		},
		beforeDestroy() {
			// 移除事件监听
			eventBus.off('userLoggedIn', this.loadUserInfo);
			// 移除事件监听
			eventBus.off('usernameChanged', this.loadUserInfo);
		}
	};
</script>

<style scoped>
	.navbar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 16rem;
		height: 4rem;
		background-color: #ffffff; /* 默认白色背景 */
		color: #333;
		transition:
			background-color 0.3s ease,
			box-shadow 0.3s ease; /* 平滑过渡效果 */
		border-bottom: 1px solid #ccc;
		box-sizing: border-box; /* 让 padding 和 border 包含在元素的总尺寸内 */
	}

	.navbar.transparent {
		background-color: transparent !important; /* 背景透明 */
		box-shadow: none !important; /* 无阴影 */
		color: white !important; /* 确保标题、菜单项和用户名变白 */
	}

	.navbar.transparent .title,
	.navbar.transparent .menu li,
	.navbar.transparent .username {
		color: white !important; /* 确保菜单项和标题变白 */
	}

	.navbar-left {
		display: flex;
		align-items: center;
	}

	.title {
		font-size: 1.5rem;
		font-weight: bold;
		margin-right: 2rem;
		color: #f87c21;
	}

	.menu {
		display: flex;
		list-style: none;
		margin: 0;
		padding: 0;
	}

	.menu li {
		margin-right: 2.5rem;
		font-size: 1rem;
		cursor: pointer;
		color: #333; /* 默认深色 */
		transition:
			color 0.3s ease,
			border-bottom 0.3s ease;
		position: relative;
	}

	.menu li:hover {
		color: #ff6a00; /* 鼠标悬停时字体变浅 */
	}

	.menu li.active {
		color: #ff6a00;
		font-weight: bold;
	}

	.navbar.transparent .menu li.active::after {
		background-color: white; /* 透明状态下的下划线变白 */
	}

	.navbar.transparent .menu li:hover {
		color: #ff6a00 !important; /* 鼠标悬停时字体变浅，确保优先级 */
	}

	.menu li.active::after {
		content: '';
		position: absolute;
		bottom: -5px;
		left: 0;
		width: 100%;
		height: 2px;
		background-color: #ff6a00;
	}

	.navbar-right {
		display: flex;
		align-items: center;
		margin-left: auto; /* 推到最右侧 */
	}

	.username {
		margin-left: 0.5rem;
		color: #333;
		cursor: pointer;
	}

	.login-text {
		cursor: pointer;
	}

	.login-text:hover {
		color: #ff6a00;
	}

	.dropdown-menu {
		list-style: none;
		padding: 0;
		margin: 0;
		background: white;
	}

	.dropdown-menu li {
		padding: 10px;
		cursor: pointer;
		text-align: center;
	}

	.dropdown-menu li:hover {
		color: #ff6a00;
		background: #f6f6f6;
	}
</style>
